"""
流式API示例 - 展示Gua框架的流式处理能力
重构版本：基于Linus设计哲学，消除重复代码
"流式处理不是特殊功能，而是响应的自然延伸"
"""

import random
from typing import Final
from os.path import join as path_join
from gua import GuaApp, respond
from gua.streaming_utils import create_simple_stream, create_sse_events, create_ai_chat_stream

app = GuaApp()

STATIC_DIR: Final[str] = "examples/static"


def static_path(*paths):
    return path_join(STATIC_DIR, *paths)


@app.route("/")
async def index():
    """首页 - 流式响应测试界面"""
    with open(static_path("streaming_api.html"), "r", encoding="utf-8") as f:
        content = f.read()
    return respond(content)


@app.route("/css/streaming_api.css")
async def style():
    """CSS样式文件"""
    with open(static_path("css", "streaming_api.css"), "r", encoding="utf-8") as f:
        content = f.read()
    return respond(content, content_type="text/css")


@app.route("/js/streaming_api.js")
async def script():
    """JavaScript文件"""
    with open(static_path("js", "streaming_api.js"), "r", encoding="utf-8") as f:
        content = f.read()
    return respond(content, content_type="application/javascript")


@app.route("/stream")
async def simple_stream():
    """基础流式响应示例 - Linus式重构：消除重复代码"""
    return create_simple_stream(data_count=10, delay=0.5)


@app.route("/quick-stream")
async def quick_stream():
    """快速流式响应示例 - Linus式重构：消除重复代码"""
    return create_simple_stream(data_count=5, delay=0.2)


@app.route("/events")
async def events_stream():
    """服务器发送事件示例 - Linus式重构：使用通用SSE生成器"""
    return create_sse_events()


@app.route("/chat-stream")
async def chat_stream():
    """AI流式响应示例 - Linus式重构：使用通用AI聊天流"""
    import asyncio
    
    # 模拟AI思考
    await asyncio.sleep(random.uniform(1.0, 2.0))
    
    responses = [
        "这是一个AI流式响应示例，模拟真实对话的逐字输出效果。你可以看到每个字符都是逐渐出现的，就像真实的AI对话一样。",
        "Gua框架让流式处理变得简单，就像这样逐字显示内容。我们的框架基于Linus的设计哲学，追求简洁和高效。",
        "基于Linus设计哲学的极简框架，每个字符都有随机延迟。这种设计让用户体验更加自然，就像与真人对话一样。",
    ]
    response = random.choice(responses)
    
    return create_ai_chat_stream(response, thinking_time=0)


if __name__ == "__main__":
    import subprocess
    import sys
    
    # 使用gua命令显示示例启动信息
    result = subprocess.run([sys.executable, "-m", "gua.cli", "examples.streaming_api:app", "--example-info"],
                          capture_output=True, text=True)
    if result.returncode == 0:
        print(result.stdout)
    else:
        print("错误: 无法显示启动信息")
        print("请手动运行: gua examples.streaming_api:app --example-info")
